package com.hgkj.cloud.customer.controller;

import com.hgkj.cloud.base.common.PageInfo;
import com.hgkj.cloud.base.domain.GraduationApplyRecord;
import com.hgkj.cloud.base.domain.GraduationFrameworks;
import com.hgkj.cloud.base.domain.TenantUsers;
import com.hgkj.cloud.base.service.GraduationApplyRecordService;
import com.hgkj.cloud.base.service.GraduationFrameworksService;
import com.hgkj.cloud.base.service.TenantUsersService;
import com.hgkj.cloud.customer.common.DataGrid;
import com.hgkj.cloud.customer.common.ResponseData;
import com.hgkj.cloud.base.domain.AdminUser;
import com.hgkj.cloud.base.service.TenantFrameworksService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

@Controller
@RequestMapping("/graduation")
public class GraduationController extends BaseController {

    @Autowired
    private GraduationApplyRecordService graduationApplyRecordService;
    @Autowired
    private GraduationFrameworksService graduationFrameworksService;
    @Autowired
    private TenantFrameworksService tenantFrameworksService;
    @Autowired
    private TenantUsersService tenantUsersService;

    /**
     * 设置毕业班
     *
     * @param request
     * @param framework_ids 毕业班班级id
     * @return
     */
    @RequestMapping("/setFrameworkGraduation")
    @ResponseBody
    public ResponseData setFrameworkGraduation(HttpServletRequest request,
                                               @RequestParam(required = true) String framework_ids, String admin_uuid) {
        ResponseData reData = new ResponseData();
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        GraduationFrameworks mframeworkGraduation = new GraduationFrameworks();
        mframeworkGraduation.setUser_uuid(adminUserInfoByUuid.getUuid());
        Map<String, Object> map = new HashMap<>();
        try {
            if (framework_ids.contains(",")) {
                String[] framework_idsList = framework_ids.split(",");
                for (int i = 0; i < framework_idsList.length; i++) {
                    String frameworkId = framework_idsList[i];
                    Long mFrameworkId = Long.valueOf(frameworkId);
                    mframeworkGraduation.setFramework_id(mFrameworkId);
                    graduationFrameworksService.insert(mframeworkGraduation);
                    tenantFrameworksService.delFramework(mFrameworkId);
                    map.put("enabled", -1);
                    map.put("framework_id", mFrameworkId);
                    tenantUsersService.updateUserType(map);
                }
            } else {
                mframeworkGraduation.setFramework_id(Long.valueOf(framework_ids));
                graduationFrameworksService.insert(mframeworkGraduation);
                tenantFrameworksService.delFramework(Long.valueOf(framework_ids));
                map.put("enabled", -1);
                map.put("framework_id", framework_ids);
                tenantUsersService.updateUserType(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("操作失败");
        }
        return reData;

    }

    /**
     * 获取本校毕业班信息
     *
     * @param request
     * @param dataGrid
     * @param beginTime
     * @param endTime
     * @param user_name
     * @param whole_name
     * @return
     */
    @RequestMapping("/getFrameworkGraduation")
    @ResponseBody
    public DataGrid getFrameworkGraduation(HttpServletRequest request, DataGrid dataGrid, String beginTime,
                                           String endTime, String user_name, String whole_name, String admin_uuid) {
        ResponseData reData = new ResponseData();
        PageInfo pi = new PageInfo();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        GraduationFrameworks mframeworkGraduation = new GraduationFrameworks();
        mframeworkGraduation.setUser_uuid(adminUserInfoByUuid.getUuid());
        Map<String, Object> map = new HashMap<>();
        if (beginTime != null && !"".equals(beginTime)) {
            map.put("beginTime", beginTime);
        }
        if (endTime != null && !"".equals(endTime)) {
            map.put("endTime", endTime);
        }
        if (user_name != null && !"".equals(user_name)) {
            map.put("user_name", user_name);
        }
        if (whole_name != null && !"".equals(whole_name)) {
            map.put("whole_name", whole_name);
        }
        map.put("channel_id", adminUserInfoByUuid.getChannel_id());

        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        List<Map<String, Object>> mFrameworkGraduationList = graduationFrameworksService.getGraduationFrameworkByMap(pi, map);
        Long count = graduationFrameworksService.getGraduationFrameworkCountByMap(map);
        dataGrid.setRows(mFrameworkGraduationList);
        dataGrid.setTotal(count);
        return dataGrid;
    }

    /**
     * 提交调档申请
     *
     * @param request
     * @param user_names 被调档人员账号
     * @return
     */
    @RequestMapping("/setGraduationApplyRecord")
    @ResponseBody
    public ResponseData setGraduationApplyRecord(HttpServletRequest request, String framework_ids, String user_names, String user_id) {
        ResponseData reData = new ResponseData();
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
        TenantUsers operator = getUserInfoById(user_id);
        List<String> mFrameworkIds = new ArrayList<>();
        List<String> mUserNamesList = new ArrayList<>();
        List<String> mUserNamesTempList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        List<String> frameworks = new ArrayList<String>();
        List<String> statuss = new ArrayList<String>();
        statuss.add("0");
        statuss.add("1");
        map.put("statuss", statuss);
        if (user_names != null) {
            if (user_names.contains("|")) {
                String[] mUserNames = user_names.split("\\|");
                mUserNamesList = new ArrayList<>(Arrays.asList(mUserNames));
            } else {
                mUserNamesList.add(user_names);
            }
            for (int k = 0; k < mUserNamesList.size(); k++) {
                map.put("user_name", mUserNamesList.get(k));
                List<Map<String, Object>> mList = graduationApplyRecordService.getGraduationApplyRecordByMap(null, map);
                if (mList != null && mList.size() != 0) {
                    mUserNamesTempList.add(mUserNamesList.get(k));
                }
            }
            mUserNamesTempList.removeAll(mUserNamesTempList);
        } else {
            reData.setCode(-1);
            reData.setMsg("user_names为空");
            return reData;
        }
        if (mUserNamesList.size() == 0) {
            reData.setCode(-1);
            reData.setMsg("请勿重复添加");
            return reData;
        }
        String prefix = "insert into graduation_apply_record(user_name,apply_id ,create_date,enabled,status) VALUES ";
        Connection conn = null;
        PreparedStatement pst = null;
        SqlSession nativeSqlSession = null;
        try {
            StringBuffer suffix = new StringBuffer();

            for (int k = 0; k < mUserNamesList.size(); k++) {
                suffix.append("('" + mUserNamesList.get(k) + "'," + operator.getId() + ",now(),1, 0),");
            }
            if (suffix.length() == 0) {
                reData.setCode(-1);
                reData.setMsg("请勿重复添加");
                return reData;
            }
            nativeSqlSession = getNativeSqlSession();
            conn = getConnection(nativeSqlSession);
            conn.setAutoCommit(false);
            pst = conn.prepareStatement(" ");
            // 构建完整sql
            String sql = prefix + suffix.substring(0, suffix.length() - 1);
            // 添加执行sql
            pst.addBatch(sql);
            // 执行操作
            pst.executeBatch();
            // 提交事务
            conn.commit();
            // 清空上一次添加的数据
            suffix = new StringBuffer();

            // 头等连接
            pst.close();
            conn.close();
        } catch (SQLException e) {
            reData.setCode(-1);
            reData.setMsg("操作失败");
            e.printStackTrace();
        } finally {
            IOclose(conn, pst, nativeSqlSession);
        }
        return reData;
    }

    /**
     * 获取毕业学生
     *
     * @param request
     * @param dataGrid
     * @return
     */
    @RequestMapping("/getGraduationStudents")
    @ResponseBody
    public DataGrid getGraduationStudents(HttpServletRequest request, DataGrid dataGrid, String user_id) {
        ResponseData reData = new ResponseData();
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
        TenantUsers operator = getUserInfoById(user_id);
        Map<String, Object> map = new HashMap<>();
        map.put("user_type", -1);
        map.put("need_disable", "need_disable");
        map.put("tenant_id", operator.getTenant_id());
        PageInfo pi = new PageInfo();

        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        try {
            List<TenantUsers> mlistUsers = tenantUsersService.listUsers(pi, map);
            Long count = tenantUsersService.listUsersCount(map);
            dataGrid.setRows(mlistUsers);
            dataGrid.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("操作失败");
        }
        return dataGrid;

    }

    /**
     * 中学端获取申请列表
     *
     * @param request
     * @param dataGrid
     * @return
     */
    @RequestMapping("/getGraduationApplyRecordHigh")
    @ResponseBody
    public DataGrid getGraduationApplyRecordHigh(HttpServletRequest request, DataGrid dataGrid,
                                                 String user_name, String real_name, Integer user_gender, String apply_name, String beginTime,
                                                 String endTime, String user_id) {
        ResponseData reData = new ResponseData();
//        User operator = (User) SecurityUtils.getSubject().getPrincipal();
        TenantUsers operator = getUserInfoById(user_id);
        PageInfo pi = new PageInfo();
        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        Map<String, Object> map = new HashMap<>();

        if (user_name != null && !"".equals(user_name)) {
            map.put("user_name", user_name);
        }
        if (real_name != null && !"".equals(real_name)) {
            map.put("real_name", real_name);
        }
        if (apply_name != null && !"".equals(apply_name)) {
            map.put("apply_name", apply_name);
        }
        if (user_gender != null) {
            map.put("user_gender", user_gender);
        }
        if (beginTime != null && !"".equals(beginTime)) {
            map.put("beginTime", beginTime);
        }
        if (endTime != null && !"".equals(endTime)) {
            map.put("endTime", endTime);
        }
        map.put("apply_tenant_id", operator.getTenant_id());
        map.put("channel_id", operator.getTop_tenant_id());
        try {
            List<Map<String, Object>> mGraduationApplyRecord = graduationApplyRecordService.getGraduationApplyRecordByMap(pi, map);
            Long count = graduationApplyRecordService.getGraduationApplyRecordCountByMap(map);
            dataGrid.setRows(mGraduationApplyRecord);
            dataGrid.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("操作失败");
        }
        return dataGrid;
    }

    /**
     * 小学端获取申请列表
     *
     * @param request
     * @param dataGrid
     * @return
     */
    @RequestMapping("/getGraduationApplyRecord")
    @ResponseBody
    public DataGrid getGraduationApplyRecord(HttpServletRequest request, DataGrid dataGrid, String user_name, String real_name,
                                             Integer user_gender, String apply_name, String beginTime,
                                             String endTime, String admin_uuid) {
        ResponseData reData = new ResponseData();
        AdminUser operator = getAdminUserInfoByUuid(admin_uuid);
        PageInfo pi = new PageInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("framework_id", operator.getFramework_id());
        map.put("channel_id", operator.getChannel_id());
        if (user_name != null && !"".equals(user_name)) {
            map.put("user_name", user_name);
        }
        if (real_name != null && !"".equals(real_name)) {
            map.put("real_name", real_name);
        }
        if (apply_name != null && !"".equals(apply_name)) {
            map.put("apply_name", apply_name);
        }
        if (user_gender != null) {
            map.put("user_gender", user_gender);
        }
        if (beginTime != null && !"".equals(beginTime)) {
            map.put("beginTime", beginTime);
        }
        if (endTime != null && !"".equals(endTime)) {
            map.put("endTime", endTime);
        }
        if (dataGrid.getPage() > 0) {
            pi.setCurrentPage(dataGrid.getPage());
            pi.setPageSize(Integer.parseInt(dataGrid.getRows().get(0).toString()));
        }
        try {
            List<Map<String, Object>> mGraduationApplyRecord = graduationApplyRecordService.getGraduationApplyRecordByMap(pi, map);
            Long count = graduationApplyRecordService.getGraduationApplyRecordCountByMap(map);
            dataGrid.setRows(mGraduationApplyRecord);
            dataGrid.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("操作失败");
        }
        return dataGrid;

    }

    /**
     * 修改申请(小学端审批  中学端修改)
     * `id`
     * `user_name`  '学生id',
     * `create_date`  '申请时间时间',
     * `apply_id`  '操作人员信息',
     * `enabled`  '1 有效  0无效 ',
     * `status`  '状态 0 未处理  1通过  -1拒绝',
     *
     * @return
     */
    @RequestMapping("/updateGraduationApplyRecord")
    @ResponseBody
    public ResponseData updateGraduationApplyRecord(HttpServletRequest request, GraduationApplyRecord mGraduationApplyRecord,
                                                    String admin_uuid) {
        ResponseData reData = new ResponseData();
        AdminUser adminUserInfoByUuid = getAdminUserInfoByUuid(admin_uuid);
        mGraduationApplyRecord.setAdmin_id(adminUserInfoByUuid.getUuid());
        try {
            graduationApplyRecordService.updateByPrimaryKeySelective(mGraduationApplyRecord);
        } catch (Exception e) {
            e.printStackTrace();
            reData.setCode(-1);
            reData.setMsg("操作失败");
        }
        return reData;
    }

//    @RequestMapping("/getHistoryUserId")
//    @ResponseBody
//    public ResponseData getHistoryUserId(Long user_id) {
//        ResponseData reData = new ResponseData();
//        try {
//            Map<String, Object> mHistoryUserId=	graduationApplyRecordService.getHistoryUserId(user_id);
//            reData.setData(mHistoryUserId);
//        } catch (Exception e) {
//            e.printStackTrace();
//            reData.setCode(-1);
//            reData.setMsg("操作失败");
//        }
//        return reData;
//    }
}
